package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能:
 * 作者: sdj
 * 日期: 2024/12/8 22:23
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/add")
    public Result add(@RequestBody User user){
        try {
            userService.save(user);   //保存一个数据
        }catch (Exception e){
            if (e instanceof DuplicateKeyException){
                return Result.error("插入数据库错误");
            }else {
                return  Result.error("系统错误");
            }
        }
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user){
        userService.updateById(user);   //根据id更新数据
        return Result.success();
    }


    @GetMapping("/selectAll")
    public Result selectAll(){
        List<User> userList=userService.list(new QueryWrapper<User>().orderByDesc("id"));  //查询所有数据根据id排序
        return Result.success(userList);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id){
       // User user=userService.getOne(new QueryWrapper<User>().eq("id",id));  //根据id查询数据
        User user=userService.getById(id); //根据id查询
        return Result.success(user);
    }

    @PostMapping("/delete/{id}")
    public Result deleteById (@PathVariable Integer id){
        boolean b = userService.removeById(id);
        if (b){
            return Result.success();
        }else {
            return Result.error("删除数据失败");
        }
    }

    @PostMapping("/delete/batch")
    public Result deleteByList(@RequestBody List<Integer> ids){
        boolean b = userService.removeBatchByIds(ids);
        if (b){
            return Result.success();
        }else {
            return Result.error("删除数据失败");
        }
    }


    /*
    * pageNum:当前页码
    * pageSize:每页显示多少条数据
    * */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam String name,
                               @RequestParam String username,
                               @RequestParam Integer pageNum,
                               @RequestParam Integer pageSize
                              ){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
        queryWrapper.like(StrUtil.isNotBlank(username),"username",username);

        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);  //多条件分页模糊查询
        return Result.success(page);
    }

    //hutool Excel导出
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String ids,
                           HttpServletResponse response) throws IOException {
        ExcelWriter excelWriter = ExcelUtil.getWriter(true);

        List<User> list;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(ids)){
            //选中行导出
            //将字符串的数据转换数字型数组
            List<Integer> idaArr = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id",idaArr);
        }else {
            //全部导出或者根据查询条件导出
            queryWrapper.like(StrUtil.isNotBlank(name),"name",name);
            queryWrapper.like(StrUtil.isNotBlank(username),"username",username);
        }
        list=userService.list(queryWrapper);

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码,中文用URLEncoder.encode("文件名","UTF-8")编码
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户表","UTF-8")+".xlsx");

        excelWriter.write(list,true);
        ServletOutputStream outputStream = response.getOutputStream();
        excelWriter.flush(outputStream,true);
        excelWriter.close();
        outputStream.flush();
        outputStream.close();
    }

    @PostMapping("/import")
    public Result importDate(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        ExcelReader writer = ExcelUtil.getReader(multipartFile.getInputStream());
        List<User> list = writer.readAll(User.class);
        try {
            userService.saveBatch(list);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
        return Result.success();
    }

}
